package com.whale.kernel.validation.constraints.impl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.whale.kernel.validation.constraints.FieldMatch;

public class FieldMatchValidator implements
		ConstraintValidator<FieldMatch, Object> {
	
	private Logger logger = LoggerFactory.getLogger(FieldMatchValidator.class);
	
	private String firstFieldName;
	private String secondFieldName;

	public void initialize(FieldMatch constraintAnnotation) {
		firstFieldName = constraintAnnotation.first();
		secondFieldName = constraintAnnotation.second();
	}

	public boolean isValid(Object value, ConstraintValidatorContext context) {
		try {
			final Object firstObj = BeanUtils
					.getProperty(value, firstFieldName);
			final Object secondObj = BeanUtils.getProperty(value,
					secondFieldName);

			if (firstObj == null && secondObj == null) {
				return true;
			}
			
			if (firstObj != null) {
				return firstObj.equals(secondObj);
			}
			return false;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return true;
	}
}
